* Changed makeSelectOptions() so that its paramater must always be an array
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
7
8 /**
9 * Depends on the CacheManager
10 */
11 require_once( 'CacheManager.php' );
12
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18
19 /** Number of times to re-try an operation in case of deadlock */
20 define( 'DEADLOCK_TRIES', 4 );
21 /** Minimum time to wait before retry, in microseconds */
22 define( 'DEADLOCK_DELAY_MIN', 500000 );
23 /** Maximum time to wait before retry */
24 define( 'DEADLOCK_DELAY_MAX', 1500000 );
25
26 /**
27 * Database abstraction object
28 * @package MediaWiki
29 */
30 class Database {
31
32 #------------------------------------------------------------------------------
33 # Variables
34 #------------------------------------------------------------------------------
35 /**#@+
36 * @access private
37 */
38 var $mLastQuery = '';
39
40 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
41 var $mOut, $mOpened = false;
42
43 var $mFailFunction;
44 var $mTablePrefix;
45 var $mFlags;
46 var $mTrxLevel = 0;
47 var $mErrorCount = 0;
48 /**#@-*/
49
50 #------------------------------------------------------------------------------
51 # Accessors
52 #------------------------------------------------------------------------------
53 # These optionally set a variable and return the previous state
54
55 /**
56 * Fail function, takes a Database as a parameter
57 * Set to false for default, 1 for ignore errors
58 */
59 function failFunction( $function = NULL ) {
60 return wfSetVar( $this->mFailFunction, $function );
61 }
62
63 /**
64 * Output page, used for reporting errors
65 * FALSE means discard output
66 */
67 function &setOutputPage( &$out ) {
68 $this->mOut =& $out;
69 }
70
71 /**
72 * Boolean, controls output of large amounts of debug information
73 */
74 function debug( $debug = NULL ) {
75 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
76 }
77
78 /**
79 * Turns buffering of SQL result sets on (true) or off (false).
80 * Default is "on" and it should not be changed without good reasons.
81 */
82 function bufferResults( $buffer = NULL ) {
83 if ( is_null( $buffer ) ) {
84 return !(bool)( $this->mFlags & DBO_NOBUFFER );
85 } else {
86 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
87 }
88 }
89
90 /**
91 * Turns on (false) or off (true) the automatic generation and sending
92 * of a "we're sorry, but there has been a database error" page on
93 * database errors. Default is on (false). When turned off, the
94 * code should use wfLastErrno() and wfLastError() to handle the
95 * situation as appropriate.
96 */
97 function ignoreErrors( $ignoreErrors = NULL ) {
98 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
99 }
100
101 /**
102 * The current depth of nested transactions
103 * @param integer $level
104 */
105 function trxLevel( $level = NULL ) {
106 return wfSetVar( $this->mTrxLevel, $level );
107 }
108
109 /**
110 * Number of errors logged, only useful when errors are ignored
111 */
112 function errorCount( $count = NULL ) {
113 return wfSetVar( $this->mErrorCount, $count );
114 }
115
116 /**#@+
117 * Get function
118 */
119 function lastQuery() { return $this->mLastQuery; }
120 function isOpen() { return $this->mOpened; }
121 /**#@-*/
122
123 #------------------------------------------------------------------------------
124 # Other functions
125 #------------------------------------------------------------------------------
126
127 /**#@+
128 * @param string $server database server host
129 * @param string $user database user name
130 * @param string $password database user password
131 * @param string $dbname database name
132 */
133
134 /**
135 * @param failFunction
136 * @param $flags
137 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
138 */
139 function Database( $server = false, $user = false, $password = false, $dbName = false,
140 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
141
142 global $wgOut, $wgDBprefix, $wgCommandLineMode;
143 # Can't get a reference if it hasn't been set yet
144 if ( !isset( $wgOut ) ) {
145 $wgOut = NULL;
146 }
147 $this->mOut =& $wgOut;
148
149 $this->mFailFunction = $failFunction;
150 $this->mFlags = $flags;
151
152 if ( $this->mFlags & DBO_DEFAULT ) {
153 if ( $wgCommandLineMode ) {
154 $this->mFlags &= ~DBO_TRX;
155 } else {
156 $this->mFlags |= DBO_TRX;
157 }
158 }
159
160 /*
161 // Faster read-only access
162 if ( wfReadOnly() ) {
163 $this->mFlags |= DBO_PERSISTENT;
164 $this->mFlags &= ~DBO_TRX;
165 }*/
166
167 /** Get the default table prefix*/
168 if ( $tablePrefix == 'get from global' ) {
169 $this->mTablePrefix = $wgDBprefix;
170 } else {
171 $this->mTablePrefix = $tablePrefix;
172 }
173
174 if ( $server ) {
175 $this->open( $server, $user, $password, $dbName );
176 }
177 }
178
179 /**
180 * @static
181 * @param failFunction
182 * @param $flags
183 */
184 function newFromParams( $server, $user, $password, $dbName,
185 $failFunction = false, $flags = 0 )
186 {
187 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
188 }
189
190 /**
191 * Usually aborts on failure
192 * If the failFunction is set to a non-zero integer, returns success
193 */
194 function open( $server, $user, $password, $dbName ) {
195 # Test for missing mysql.so
196 # First try to load it
197 if (!@extension_loaded('mysql')) {
198 @dl('mysql.so');
199 }
200
201 # Otherwise we get a suppressed fatal error, which is very hard to track down
202 if ( !function_exists( 'mysql_connect' ) ) {
203 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
204 }
205
206 $this->close();
207 $this->mServer = $server;
208 $this->mUser = $user;
209 $this->mPassword = $password;
210 $this->mDBname = $dbName;
211
212 $success = false;
213
214 if ( $this->mFlags & DBO_PERSISTENT ) {
215 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
216 } else {
217 @/**/$this->mConn = mysql_connect( $server, $user, $password );
218 }
219
220 if ( $dbName != '' ) {
221 if ( $this->mConn !== false ) {
222 $success = @/**/mysql_select_db( $dbName, $this->mConn );
223 if ( !$success ) {
224 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
225 }
226 } else {
227 wfDebug( "DB connection error\n" );
228 wfDebug( "Server: $server, User: $user, Password: " .
229 substr( $password, 0, 3 ) . "...\n" );
230 $success = false;
231 }
232 } else {
233 # Delay USE query
234 $success = !!$this->mConn;
235 }
236
237 if ( !$success ) {
238 $this->reportConnectionError();
239 $this->close();
240 }
241 $this->mOpened = $success;
242 return $success;
243 }
244 /**#@-*/
245
246 /**
247 * Closes a database connection.
248 * if it is open : commits any open transactions
249 *
250 * @return bool operation success. true if already closed.
251 */
252 function close()
253 {
254 $this->mOpened = false;
255 if ( $this->mConn ) {
256 if ( $this->trxLevel() ) {
257 $this->immediateCommit();
258 }
259 return mysql_close( $this->mConn );
260 } else {
261 return true;
262 }
263 }
264
265 /**
266 * @access private
267 * @param string $msg error message ?
268 * @todo parameter $msg is not used
269 */
270 function reportConnectionError( $msg = '') {
271 if ( $this->mFailFunction ) {
272 if ( !is_int( $this->mFailFunction ) ) {
273 $ff = $this->mFailFunction;
274 $ff( $this, mysql_error() );
275 }
276 } else {
277 wfEmergencyAbort( $this, mysql_error() );
278 }
279 }
280
281 /**
282 * Usually aborts on failure
283 * If errors are explicitly ignored, returns success
284 */
285 function query( $sql, $fname = '', $tempIgnore = false ) {
286 global $wgProfiling, $wgCommandLineMode;
287
288 if ( $wgProfiling ) {
289 # generalizeSQL will probably cut down the query to reasonable
290 # logging size most of the time. The substr is really just a sanity check.
291 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
292 wfProfileIn( 'Database::query' );
293 wfProfileIn( $profName );
294 }
295
296 $this->mLastQuery = $sql;
297
298 # Add a comment for easy SHOW PROCESSLIST interpretation
299 if ( $fname ) {
300 $commentedSql = "/* $fname */ $sql";
301 } else {
302 $commentedSql = $sql;
303 }
304
305 # If DBO_TRX is set, start a transaction
306 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
307 $this->begin();
308 }
309
310 if ( $this->debug() ) {
311 $sqlx = substr( $sql, 0, 500 );
312 $sqlx = strtr($sqlx,"\t\n",' ');
313 wfDebug( "SQL: $sqlx\n" );
314 }
315
316 # Do the query and handle errors
317 $ret = $this->doQuery( $commentedSql );
318
319 # Try reconnecting if the connection was lost
320 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
321 # Transaction is gone, like it or not
322 $this->mTrxLevel = 0;
323 wfDebug( "Connection lost, reconnecting...\n" );
324 if ( $this->ping() ) {
325 wfDebug( "Reconnected\n" );
326 $ret = $this->doQuery( $commentedSql );
327 } else {
328 wfDebug( "Failed\n" );
329 }
330 }
331
332 if ( false === $ret ) {
333 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
334 }
335
336 if ( $wgProfiling ) {
337 wfProfileOut( $profName );
338 wfProfileOut( 'Database::query' );
339 }
340 return $ret;
341 }
342
343 /**
344 * The DBMS-dependent part of query()
345 * @param string $sql SQL query.
346 */
347 function doQuery( $sql ) {
348 if( $this->bufferResults() ) {
349 $ret = mysql_query( $sql, $this->mConn );
350 } else {
351 $ret = mysql_unbuffered_query( $sql, $this->mConn );
352 }
353 return $ret;
354 }
355
356 /**
357 * @param $error
358 * @param $errno
359 * @param $sql
360 * @param string $fname
361 * @param bool $tempIgnore
362 */
363 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
364 global $wgCommandLineMode, $wgFullyInitialised;
365 # Ignore errors during error handling to avoid infinite recursion
366 $ignore = $this->ignoreErrors( true );
367 $this->mErrorCount ++;
368
369 if( $ignore || $tempIgnore ) {
370 wfDebug("SQL ERROR (ignored): " . $error . "\n");
371 } else {
372 $sql1line = str_replace( "\n", "\\n", $sql );
373 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
374 wfDebug("SQL ERROR: " . $error . "\n");
375 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
376 $message = "A database error has occurred\n" .
377 "Query: $sql\n" .
378 "Function: $fname\n" .
379 "Error: $errno $error\n";
380 if ( !$wgCommandLineMode ) {
381 $message = nl2br( $message );
382 }
383 wfDebugDieBacktrace( $message );
384 } else {
385 // this calls wfAbruptExit()
386 $this->mOut->databaseError( $fname, $sql, $error, $errno );
387 }
388 }
389 $this->ignoreErrors( $ignore );
390 }
391
392
393 /**
394 * Intended to be compatible with the PEAR::DB wrapper functions.
395 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
396 *
397 * ? = scalar value, quoted as necessary
398 * ! = raw SQL bit (a function for instance)
399 * & = filename; reads the file and inserts as a blob
400 * (we don't use this though...)
401 */
402 function prepare( $sql, $func = 'Database::prepare' ) {
403 /* MySQL doesn't support prepared statements (yet), so just
404 pack up the query for reference. We'll manually replace
405 the bits later. */
406 return array( 'query' => $sql, 'func' => $func );
407 }
408
409 function freePrepared( $prepared ) {
410 /* No-op for MySQL */
411 }
412
413 /**
414 * Execute a prepared query with the various arguments
415 * @param string $prepared the prepared sql
416 * @param mixed $args Either an array here, or put scalars as varargs
417 */
418 function execute( $prepared, $args = null ) {
419 if( !is_array( $args ) ) {
420 # Pull the var args
421 $args = func_get_args();
422 array_shift( $args );
423 }
424 $sql = $this->fillPrepared( $prepared['query'], $args );
425 return $this->query( $sql, $prepared['func'] );
426 }
427
428 /**
429 * Prepare & execute an SQL statement, quoting and inserting arguments
430 * in the appropriate places.
431 * @param string $query
432 * @param string $args (default null)
433 */
434 function safeQuery( $query, $args = null ) {
435 $prepared = $this->prepare( $query, 'Database::safeQuery' );
436 if( !is_array( $args ) ) {
437 # Pull the var args
438 $args = func_get_args();
439 array_shift( $args );
440 }
441 $retval = $this->execute( $prepared, $args );
442 $this->freePrepared( $prepared );
443 return $retval;
444 }
445
446 /**
447 * For faking prepared SQL statements on DBs that don't support
448 * it directly.
449 * @param string $preparedSql - a 'preparable' SQL statement
450 * @param array $args - array of arguments to fill it with
451 * @return string executable SQL
452 */
453 function fillPrepared( $preparedQuery, $args ) {
454 $n = 0;
455 reset( $args );
456 $this->preparedArgs =& $args;
457 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
458 array( &$this, 'fillPreparedArg' ), $preparedQuery );
459 }
460
461 /**
462 * preg_callback func for fillPrepared()
463 * The arguments should be in $this->preparedArgs and must not be touched
464 * while we're doing this.
465 *
466 * @param array $matches
467 * @return string
468 * @access private
469 */
470 function fillPreparedArg( $matches ) {
471 switch( $matches[1] ) {
472 case '\\?': return '?';
473 case '\\!': return '!';
474 case '\\&': return '&';
475 }
476 list( $n, $arg ) = each( $this->preparedArgs );
477 switch( $matches[1] ) {
478 case '?': return $this->addQuotes( $arg );
479 case '!': return $arg;
480 case '&':
481 # return $this->addQuotes( file_get_contents( $arg ) );
482 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
483 default:
484 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
485 }
486 }
487
488 /**#@+
489 * @param mixed $res A SQL result
490 */
491 /**
492 * Free a result object
493 */
494 function freeResult( $res ) {
495 if ( !@/**/mysql_free_result( $res ) ) {
496 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
497 }
498 }
499
500 /**
501 * Fetch the next row from the given result object, in object form
502 */
503 function fetchObject( $res ) {
504 @/**/$row = mysql_fetch_object( $res );
505 if( mysql_errno() ) {
506 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
507 }
508 return $row;
509 }
510
511 /**
512 * Fetch the next row from the given result object
513 * Returns an array
514 */
515 function fetchRow( $res ) {
516 @/**/$row = mysql_fetch_array( $res );
517 if (mysql_errno() ) {
518 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
519 }
520 return $row;
521 }
522
523 /**
524 * Get the number of rows in a result object
525 */
526 function numRows( $res ) {
527 @/**/$n = mysql_num_rows( $res );
528 if( mysql_errno() ) {
529 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
530 }
531 return $n;
532 }
533
534 /**
535 * Get the number of fields in a result object
536 * See documentation for mysql_num_fields()
537 */
538 function numFields( $res ) { return mysql_num_fields( $res ); }
539
540 /**
541 * Get a field name in a result object
542 * See documentation for mysql_field_name()
543 */
544 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
545
546 /**
547 * Get the inserted value of an auto-increment row
548 *
549 * The value inserted should be fetched from nextSequenceValue()
550 *
551 * Example:
552 * $id = $dbw->nextSequenceValue('page_page_id_seq');
553 * $dbw->insert('page',array('page_id' => $id));
554 * $id = $dbw->insertId();
555 */
556 function insertId() { return mysql_insert_id( $this->mConn ); }
557
558 /**
559 * Change the position of the cursor in a result object
560 * See mysql_data_seek()
561 */
562 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
563
564 /**
565 * Get the last error number
566 * See mysql_errno()
567 */
568 function lastErrno() {
569 if ( $this->mConn ) {
570 return mysql_errno( $this->mConn );
571 } else {
572 return mysql_errno();
573 }
574 }
575
576 /**
577 * Get a description of the last error
578 * See mysql_error() for more details
579 */
580 function lastError() {
581 if ( $this->mConn ) {
582 $error = mysql_error( $this->mConn );
583 } else {
584 $error = mysql_error();
585 }
586 if( $error ) {
587 $error .= ' (' . $this->mServer . ')';
588 }
589 return $error;
590 }
591 /**
592 * Get the number of rows affected by the last write query
593 * See mysql_affected_rows() for more details
594 */
595 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
596 /**#@-*/ // end of template : @param $result
597
598 /**
599 * Simple UPDATE wrapper
600 * Usually aborts on failure
601 * If errors are explicitly ignored, returns success
602 *
603 * This function exists for historical reasons, Database::update() has a more standard
604 * calling convention and feature set
605 */
606 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
607 {
608 $table = $this->tableName( $table );
609 $sql = "UPDATE $table SET $var = '" .
610 $this->strencode( $value ) . "' WHERE ($cond)";
611 return !!$this->query( $sql, DB_MASTER, $fname );
612 }
613
614 /**
615 * Simple SELECT wrapper, returns a single field, input must be encoded
616 * Usually aborts on failure
617 * If errors are explicitly ignored, returns FALSE on failure
618 */
619 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
620 if ( !is_array( $options ) ) {
621 $options = array( $options );
622 }
623 $options['LIMIT'] = 1;
624
625 $res = $this->select( $table, $var, $cond, $fname, $options );
626 if ( $res === false || !$this->numRows( $res ) ) {
627 return false;
628 }
629 $row = $this->fetchRow( $res );
630 if ( $row !== false ) {
631 $this->freeResult( $res );
632 return $row[0];
633 } else {
634 return false;
635 }
636 }
637
638 /**
639 * Returns an optional USE INDEX clause to go after the table, and a
640 * string to go at the end of the query
641 *
642 * @access private
643 *
644 * @param array $options an associative array of options to be turned into
645 * an SQL query, valid keys are listed in the function.
646 * @return array
647 */
648 function makeSelectOptions( $options ) {
649 $tailOpts = '';
650
651 if ( isset( $options['ORDER BY'] ) ) {
652 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
653 }
654 if ( isset( $options['LIMIT'] ) ) {
655 $tailOpts .= " LIMIT {$options['LIMIT']}";
656 }
657
658 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
659 $tailOpts .= ' FOR UPDATE';
660 }
661
662 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
663 $tailOpts .= ' LOCK IN SHARE MODE';
664 }
665
666 if ( isset( $options['USE INDEX'] ) ) {
667 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
668 } else {
669 $useIndex = '';
670 }
671 return array( $useIndex, $tailOpts );
672 }
673
674 /**
675 * SELECT wrapper
676 */
677 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
678 {
679 if( is_array( $vars ) ) {
680 $vars = implode( ',', $vars );
681 }
682 if( is_array( $table ) ) {
683 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
684 } elseif ($table!='') {
685 $from = ' FROM ' .$this->tableName( $table );
686 } else {
687 $from = '';
688 }
689
690 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( (array)$options );
691
692 if( !empty( $conds ) ) {
693 if ( is_array( $conds ) ) {
694 $conds = $this->makeList( $conds, LIST_AND );
695 }
696 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
697 } else {
698 $sql = "SELECT $vars $from $useIndex $tailOpts";
699 }
700 return $this->query( $sql, $fname );
701 }
702
703 /**
704 * Single row SELECT wrapper
705 * Aborts or returns FALSE on error
706 *
707 * $vars: the selected variables
708 * $conds: a condition map, terms are ANDed together.
709 * Items with numeric keys are taken to be literal conditions
710 * Takes an array of selected variables, and a condition map, which is ANDed
711 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
712 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
713 * $obj- >page_id is the ID of the Astronomy article
714 *
715 * @todo migrate documentation to phpdocumentor format
716 */
717 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
718 $options['LIMIT'] = 1;
719 $res = $this->select( $table, $vars, $conds, $fname, $options );
720 if ( $res === false || !$this->numRows( $res ) ) {
721 return false;
722 }
723 $obj = $this->fetchObject( $res );
724 $this->freeResult( $res );
725 return $obj;
726
727 }
728
729 /**
730 * Removes most variables from an SQL query and replaces them with X or N for numbers.
731 * It's only slightly flawed. Don't use for anything important.
732 *
733 * @param string $sql A SQL Query
734 * @static
735 */
736 function generalizeSQL( $sql ) {
737 # This does the same as the regexp below would do, but in such a way
738 # as to avoid crashing php on some large strings.
739 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
740
741 $sql = str_replace ( "\\\\", '', $sql);
742 $sql = str_replace ( "\\'", '', $sql);
743 $sql = str_replace ( "\\\"", '', $sql);
744 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
745 $sql = preg_replace ('/".*"/s', "'X'", $sql);
746
747 # All newlines, tabs, etc replaced by single space
748 $sql = preg_replace ( "/\s+/", ' ', $sql);
749
750 # All numbers => N
751 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
752
753 return $sql;
754 }
755
756 /**
757 * Determines whether a field exists in a table
758 * Usually aborts on failure
759 * If errors are explicitly ignored, returns NULL on failure
760 */
761 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
762 $table = $this->tableName( $table );
763 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
764 if ( !$res ) {
765 return NULL;
766 }
767
768 $found = false;
769
770 while ( $row = $this->fetchObject( $res ) ) {
771 if ( $row->Field == $field ) {
772 $found = true;
773 break;
774 }
775 }
776 return $found;
777 }
778
779 /**
780 * Determines whether an index exists
781 * Usually aborts on failure
782 * If errors are explicitly ignored, returns NULL on failure
783 */
784 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
785 $info = $this->indexInfo( $table, $index, $fname );
786 if ( is_null( $info ) ) {
787 return NULL;
788 } else {
789 return $info !== false;
790 }
791 }
792
793
794 /**
795 * Get information about an index into an object
796 * Returns false if the index does not exist
797 */
798 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
799 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
800 # SHOW INDEX should work for 3.x and up:
801 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
802 $table = $this->tableName( $table );
803 $sql = 'SHOW INDEX FROM '.$table;
804 $res = $this->query( $sql, $fname );
805 if ( !$res ) {
806 return NULL;
807 }
808
809 while ( $row = $this->fetchObject( $res ) ) {
810 if ( $row->Key_name == $index ) {
811 return $row;
812 }
813 }
814 return false;
815 }
816
817 /**
818 * Query whether a given table exists
819 */
820 function tableExists( $table ) {
821 $table = $this->tableName( $table );
822 $old = $this->ignoreErrors( true );
823 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
824 $this->ignoreErrors( $old );
825 if( $res ) {
826 $this->freeResult( $res );
827 return true;
828 } else {
829 return false;
830 }
831 }
832
833 /**
834 * mysql_fetch_field() wrapper
835 * Returns false if the field doesn't exist
836 *
837 * @param $table
838 * @param $field
839 */
840 function fieldInfo( $table, $field ) {
841 $table = $this->tableName( $table );
842 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
843 $n = mysql_num_fields( $res );
844 for( $i = 0; $i < $n; $i++ ) {
845 $meta = mysql_fetch_field( $res, $i );
846 if( $field == $meta->name ) {
847 return $meta;
848 }
849 }
850 return false;
851 }
852
853 /**
854 * mysql_field_type() wrapper
855 */
856 function fieldType( $res, $index ) {
857 return mysql_field_type( $res, $index );
858 }
859
860 /**
861 * Determines if a given index is unique
862 */
863 function indexUnique( $table, $index ) {
864 $indexInfo = $this->indexInfo( $table, $index );
865 if ( !$indexInfo ) {
866 return NULL;
867 }
868 return !$indexInfo->Non_unique;
869 }
870
871 /**
872 * INSERT wrapper, inserts an array into a table
873 *
874 * $a may be a single associative array, or an array of these with numeric keys, for
875 * multi-row insert.
876 *
877 * Usually aborts on failure
878 * If errors are explicitly ignored, returns success
879 */
880 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
881 # No rows to insert, easy just return now
882 if ( !count( $a ) ) {
883 return true;
884 }
885
886 $table = $this->tableName( $table );
887 if ( !is_array( $options ) ) {
888 $options = array( $options );
889 }
890 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
891 $multi = true;
892 $keys = array_keys( $a[0] );
893 } else {
894 $multi = false;
895 $keys = array_keys( $a );
896 }
897
898 $sql = 'INSERT ' . implode( ' ', $options ) .
899 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
900
901 if ( $multi ) {
902 $first = true;
903 foreach ( $a as $row ) {
904 if ( $first ) {
905 $first = false;
906 } else {
907 $sql .= ',';
908 }
909 $sql .= '(' . $this->makeList( $row ) . ')';
910 }
911 } else {
912 $sql .= '(' . $this->makeList( $a ) . ')';
913 }
914 return !!$this->query( $sql, $fname );
915 }
916
917 /**
918 * UPDATE wrapper, takes a condition array and a SET array
919 */
920 function update( $table, $values, $conds, $fname = 'Database::update' ) {
921 $table = $this->tableName( $table );
922 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
923 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
924 $this->query( $sql, $fname );
925 }
926
927 /**
928 * Makes a wfStrencoded list from an array
929 * $mode: LIST_COMMA - comma separated, no field names
930 * LIST_AND - ANDed WHERE clause (without the WHERE)
931 * LIST_SET - comma separated with field names, like a SET clause
932 * LIST_NAMES - comma separated field names
933 */
934 function makeList( $a, $mode = LIST_COMMA ) {
935 if ( !is_array( $a ) ) {
936 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
937 }
938
939 $first = true;
940 $list = '';
941 foreach ( $a as $field => $value ) {
942 if ( !$first ) {
943 if ( $mode == LIST_AND ) {
944 $list .= ' AND ';
945 } else {
946 $list .= ',';
947 }
948 } else {
949 $first = false;
950 }
951 if ( $mode == LIST_AND && is_numeric( $field ) ) {
952 $list .= "($value)";
953 } elseif ( $mode == LIST_AND && is_array ($value) ) {
954 $list .= $field." IN (".$this->makeList($value).") ";
955 } else {
956 if ( $mode == LIST_AND || $mode == LIST_SET ) {
957 $list .= $field.'=';
958 }
959 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
960 }
961 }
962 return $list;
963 }
964
965 /**
966 * Change the current database
967 */
968 function selectDB( $db ) {
969 $this->mDBname = $db;
970 return mysql_select_db( $db, $this->mConn );
971 }
972
973 /**
974 * Starts a timer which will kill the DB thread after $timeout seconds
975 */
976 function startTimer( $timeout ) {
977 global $IP;
978 if( function_exists( 'mysql_thread_id' ) ) {
979 # This will kill the query if it's still running after $timeout seconds.
980 $tid = mysql_thread_id( $this->mConn );
981 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
982 }
983 }
984
985 /**
986 * Stop a timer started by startTimer()
987 * Currently unimplemented.
988 *
989 */
990 function stopTimer() { }
991
992 /**
993 * Format a table name ready for use in constructing an SQL query
994 *
995 * This does two important things: it quotes table names which as necessary,
996 * and it adds a table prefix if there is one.
997 *
998 * All functions of this object which require a table name call this function
999 * themselves. Pass the canonical name to such functions. This is only needed
1000 * when calling query() directly.
1001 *
1002 * @param string $name database table name
1003 */
1004 function tableName( $name ) {
1005 global $wgSharedDB;
1006 # Skip quoted literals
1007 if ( $name{0} != '`' ) {
1008 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1009 $name = "{$this->mTablePrefix}$name";
1010 }
1011 if ( isset( $wgSharedDB ) && 'user' == $name ) {
1012 $name = "`$wgSharedDB`.`$name`";
1013 } else {
1014 # Standard quoting
1015 $name = "`$name`";
1016 }
1017 }
1018 return $name;
1019 }
1020
1021 /**
1022 * Fetch a number of table names into an array
1023 * This is handy when you need to construct SQL for joins
1024 *
1025 * Example:
1026 * extract($dbr->tableNames('user','watchlist'));
1027 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1028 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1029 */
1030 function tableNames() {
1031 $inArray = func_get_args();
1032 $retVal = array();
1033 foreach ( $inArray as $name ) {
1034 $retVal[$name] = $this->tableName( $name );
1035 }
1036 return $retVal;
1037 }
1038
1039 /**
1040 * Wrapper for addslashes()
1041 * @param string $s String to be slashed.
1042 * @return string slashed string.
1043 */
1044 function strencode( $s ) {
1045 return addslashes( $s );
1046 }
1047
1048 /**
1049 * If it's a string, adds quotes and backslashes
1050 * Otherwise returns as-is
1051 */
1052 function addQuotes( $s ) {
1053 if ( is_null( $s ) ) {
1054 return 'NULL';
1055 } else {
1056 # This will also quote numeric values. This should be harmless,
1057 # and protects against weird problems that occur when they really
1058 # _are_ strings such as article titles and string->number->string
1059 # conversion is not 1:1.
1060 return "'" . $this->strencode( $s ) . "'";
1061 }
1062 }
1063
1064 /**
1065 * Returns an appropriately quoted sequence value for inserting a new row.
1066 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1067 * subclass will return an integer, and save the value for insertId()
1068 */
1069 function nextSequenceValue( $seqName ) {
1070 return NULL;
1071 }
1072
1073 /**
1074 * USE INDEX clause
1075 * PostgreSQL doesn't have them and returns ""
1076 */
1077 function useIndexClause( $index ) {
1078 return "USE INDEX ($index)";
1079 }
1080
1081 /**
1082 * REPLACE query wrapper
1083 * PostgreSQL simulates this with a DELETE followed by INSERT
1084 * $row is the row to insert, an associative array
1085 * $uniqueIndexes is an array of indexes. Each element may be either a
1086 * field name or an array of field names
1087 *
1088 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1089 * However if you do this, you run the risk of encountering errors which wouldn't have
1090 * occurred in MySQL
1091 *
1092 * @todo migrate comment to phodocumentor format
1093 */
1094 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1095 $table = $this->tableName( $table );
1096
1097 # Single row case
1098 if ( !is_array( reset( $rows ) ) ) {
1099 $rows = array( $rows );
1100 }
1101
1102 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1103 $first = true;
1104 foreach ( $rows as $row ) {
1105 if ( $first ) {
1106 $first = false;
1107 } else {
1108 $sql .= ',';
1109 }
1110 $sql .= '(' . $this->makeList( $row ) . ')';
1111 }
1112 return $this->query( $sql, $fname );
1113 }
1114
1115 /**
1116 * DELETE where the condition is a join
1117 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1118 *
1119 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1120 * join condition matches, set $conds='*'
1121 *
1122 * DO NOT put the join condition in $conds
1123 *
1124 * @param string $delTable The table to delete from.
1125 * @param string $joinTable The other table.
1126 * @param string $delVar The variable to join on, in the first table.
1127 * @param string $joinVar The variable to join on, in the second table.
1128 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1129 */
1130 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1131 if ( !$conds ) {
1132 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1133 }
1134
1135 $delTable = $this->tableName( $delTable );
1136 $joinTable = $this->tableName( $joinTable );
1137 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1138 if ( $conds != '*' ) {
1139 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1140 }
1141
1142 return $this->query( $sql, $fname );
1143 }
1144
1145 /**
1146 * Returns the size of a text field, or -1 for "unlimited"
1147 */
1148 function textFieldSize( $table, $field ) {
1149 $table = $this->tableName( $table );
1150 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1151 $res = $this->query( $sql, 'Database::textFieldSize' );
1152 $row = $this->fetchObject( $res );
1153 $this->freeResult( $res );
1154
1155 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1156 $size = $m[1];
1157 } else {
1158 $size = -1;
1159 }
1160 return $size;
1161 }
1162
1163 /**
1164 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1165 */
1166 function lowPriorityOption() {
1167 return 'LOW_PRIORITY';
1168 }
1169
1170 /**
1171 * DELETE query wrapper
1172 *
1173 * Use $conds == "*" to delete all rows
1174 */
1175 function delete( $table, $conds, $fname = 'Database::delete' ) {
1176 if ( !$conds ) {
1177 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1178 }
1179 $table = $this->tableName( $table );
1180 $sql = "DELETE FROM $table";
1181 if ( $conds != '*' ) {
1182 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1183 }
1184 return $this->query( $sql, $fname );
1185 }
1186
1187 /**
1188 * INSERT SELECT wrapper
1189 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1190 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1191 * $conds may be "*" to copy the whole table
1192 * srcTable may be an array of tables.
1193 */
1194 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1195 $destTable = $this->tableName( $destTable );
1196 if( is_array( $srcTable ) ) {
1197 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1198 } else {
1199 $srcTable = $this->tableName( $srcTable );
1200 }
1201 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1202 ' SELECT ' . implode( ',', $varMap ) .
1203 " FROM $srcTable";
1204 if ( $conds != '*' ) {
1205 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1206 }
1207 return $this->query( $sql, $fname );
1208 }
1209
1210 /**
1211 * Construct a LIMIT query with optional offset
1212 * This is used for query pages
1213 */
1214 function limitResult($limit,$offset) {
1215 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1216 }
1217
1218 /**
1219 * Returns an SQL expression for a simple conditional.
1220 * Uses IF on MySQL.
1221 *
1222 * @param string $cond SQL expression which will result in a boolean value
1223 * @param string $trueVal SQL expression to return if true
1224 * @param string $falseVal SQL expression to return if false
1225 * @return string SQL fragment
1226 */
1227 function conditional( $cond, $trueVal, $falseVal ) {
1228 return " IF($cond, $trueVal, $falseVal) ";
1229 }
1230
1231 /**
1232 * Determines if the last failure was due to a deadlock
1233 */
1234 function wasDeadlock() {
1235 return $this->lastErrno() == 1213;
1236 }
1237
1238 /**
1239 * Perform a deadlock-prone transaction.
1240 *
1241 * This function invokes a callback function to perform a set of write
1242 * queries. If a deadlock occurs during the processing, the transaction
1243 * will be rolled back and the callback function will be called again.
1244 *
1245 * Usage:
1246 * $dbw->deadlockLoop( callback, ... );
1247 *
1248 * Extra arguments are passed through to the specified callback function.
1249 *
1250 * Returns whatever the callback function returned on its successful,
1251 * iteration, or false on error, for example if the retry limit was
1252 * reached.
1253 */
1254 function deadlockLoop() {
1255 $myFname = 'Database::deadlockLoop';
1256
1257 $this->query( 'BEGIN', $myFname );
1258 $args = func_get_args();
1259 $function = array_shift( $args );
1260 $oldIgnore = $this->ignoreErrors( true );
1261 $tries = DEADLOCK_TRIES;
1262 if ( is_array( $function ) ) {
1263 $fname = $function[0];
1264 } else {
1265 $fname = $function;
1266 }
1267 do {
1268 $retVal = call_user_func_array( $function, $args );
1269 $error = $this->lastError();
1270 $errno = $this->lastErrno();
1271 $sql = $this->lastQuery();
1272
1273 if ( $errno ) {
1274 if ( $this->wasDeadlock() ) {
1275 # Retry
1276 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1277 } else {
1278 $this->reportQueryError( $error, $errno, $sql, $fname );
1279 }
1280 }
1281 } while( $this->wasDeadlock() && --$tries > 0 );
1282 $this->ignoreErrors( $oldIgnore );
1283 if ( $tries <= 0 ) {
1284 $this->query( 'ROLLBACK', $myFname );
1285 $this->reportQueryError( $error, $errno, $sql, $fname );
1286 return false;
1287 } else {
1288 $this->query( 'COMMIT', $myFname );
1289 return $retVal;
1290 }
1291 }
1292
1293 /**
1294 * Do a SELECT MASTER_POS_WAIT()
1295 *
1296 * @param string $file the binlog file
1297 * @param string $pos the binlog position
1298 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1299 */
1300 function masterPosWait( $file, $pos, $timeout ) {
1301 $fname = 'Database::masterPosWait';
1302 wfProfileIn( $fname );
1303
1304
1305 # Commit any open transactions
1306 $this->immediateCommit();
1307
1308 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1309 $encFile = $this->strencode( $file );
1310 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1311 $res = $this->doQuery( $sql );
1312 if ( $res && $row = $this->fetchRow( $res ) ) {
1313 $this->freeResult( $res );
1314 return $row[0];
1315 } else {
1316 return false;
1317 }
1318 }
1319
1320 /**
1321 * Get the position of the master from SHOW SLAVE STATUS
1322 */
1323 function getSlavePos() {
1324 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1325 $row = $this->fetchObject( $res );
1326 if ( $row ) {
1327 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1328 } else {
1329 return array( false, false );
1330 }
1331 }
1332
1333 /**
1334 * Get the position of the master from SHOW MASTER STATUS
1335 */
1336 function getMasterPos() {
1337 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1338 $row = $this->fetchObject( $res );
1339 if ( $row ) {
1340 return array( $row->File, $row->Position );
1341 } else {
1342 return array( false, false );
1343 }
1344 }
1345
1346 /**
1347 * Begin a transaction, or if a transaction has already started, continue it
1348 */
1349 function begin( $fname = 'Database::begin' ) {
1350 if ( !$this->mTrxLevel ) {
1351 $this->immediateBegin( $fname );
1352 } else {
1353 $this->mTrxLevel++;
1354 }
1355 }
1356
1357 /**
1358 * End a transaction, or decrement the nest level if transactions are nested
1359 */
1360 function commit( $fname = 'Database::commit' ) {
1361 if ( $this->mTrxLevel ) {
1362 $this->mTrxLevel--;
1363 }
1364 if ( !$this->mTrxLevel ) {
1365 $this->immediateCommit( $fname );
1366 }
1367 }
1368
1369 /**
1370 * Rollback a transaction
1371 */
1372 function rollback( $fname = 'Database::rollback' ) {
1373 $this->query( 'ROLLBACK', $fname );
1374 $this->mTrxLevel = 0;
1375 }
1376
1377 /**
1378 * Begin a transaction, committing any previously open transaction
1379 */
1380 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1381 $this->query( 'BEGIN', $fname );
1382 $this->mTrxLevel = 1;
1383 }
1384
1385 /**
1386 * Commit transaction, if one is open
1387 */
1388 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1389 $this->query( 'COMMIT', $fname );
1390 $this->mTrxLevel = 0;
1391 }
1392
1393 /**
1394 * Return MW-style timestamp used for MySQL schema
1395 */
1396 function timestamp( $ts=0 ) {
1397 return wfTimestamp(TS_MW,$ts);
1398 }
1399
1400 /**
1401 * Local database timestamp format or null
1402 */
1403 function timestampOrNull( $ts = null ) {
1404 if( is_null( $ts ) ) {
1405 return null;
1406 } else {
1407 return $this->timestamp( $ts );
1408 }
1409 }
1410
1411 /**
1412 * @todo document
1413 */
1414 function &resultObject( &$result ) {
1415 if( empty( $result ) ) {
1416 return NULL;
1417 } else {
1418 return new ResultWrapper( $this, $result );
1419 }
1420 }
1421
1422 /**
1423 * Return aggregated value alias
1424 */
1425 function aggregateValue ($valuedata,$valuename='value') {
1426 return $valuename;
1427 }
1428
1429 /**
1430 * @return string wikitext of a link to the server software's web site
1431 */
1432 function getSoftwareLink() {
1433 return "[http://www.mysql.com/ MySQL]";
1434 }
1435
1436 /**
1437 * @return string Version information from the database
1438 */
1439 function getServerVersion() {
1440 return mysql_get_server_info();
1441 }
1442
1443 /**
1444 * Ping the server and try to reconnect if it there is no connection
1445 */
1446 function ping() {
1447 return mysql_ping( $this->mConn );
1448 }
1449 }
1450
1451 /**
1452 * Database abstraction object for mySQL
1453 * Inherit all methods and properties of Database::Database()
1454 *
1455 * @package MediaWiki
1456 * @see Database
1457 */
1458 class DatabaseMysql extends Database {
1459 # Inherit all
1460 }
1461
1462
1463 /**
1464 * Result wrapper for grabbing data queried by someone else
1465 *
1466 * @package MediaWiki
1467 */
1468 class ResultWrapper {
1469 var $db, $result;
1470
1471 /**
1472 * @todo document
1473 */
1474 function ResultWrapper( $database, $result ) {
1475 $this->db =& $database;
1476 $this->result =& $result;
1477 }
1478
1479 /**
1480 * @todo document
1481 */
1482 function numRows() {
1483 return $this->db->numRows( $this->result );
1484 }
1485
1486 /**
1487 * @todo document
1488 */
1489 function &fetchObject() {
1490 return $this->db->fetchObject( $this->result );
1491 }
1492
1493 /**
1494 * @todo document
1495 */
1496 function &fetchRow() {
1497 return $this->db->fetchRow( $this->result );
1498 }
1499
1500 /**
1501 * @todo document
1502 */
1503 function free() {
1504 $this->db->freeResult( $this->result );
1505 unset( $this->result );
1506 unset( $this->db );
1507 }
1508
1509 function seek( $row ) {
1510 $this->db->dataSeek( $this->result, $row );
1511 }
1512 }
1513
1514 #------------------------------------------------------------------------------
1515 # Global functions
1516 #------------------------------------------------------------------------------
1517
1518 /**
1519 * Standard fail function, called by default when a connection cannot be
1520 * established.
1521 * Displays the file cache if possible
1522 */
1523 function wfEmergencyAbort( &$conn, $error ) {
1524 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1525 global $wgSitename, $wgServer;
1526
1527 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1528 # Hard coding strings instead.
1529
1530 $noconnect = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server. <br />
1531 $1';
1532 $mainpage = 'Main Page';
1533 $searchdisabled = <<<EOT
1534 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1535 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1536 EOT;
1537
1538 $googlesearch = "
1539 <!-- SiteSearch Google -->
1540 <FORM method=GET action=\"http://www.google.com/search\">
1541 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1542 <A HREF=\"http://www.google.com/\">
1543 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1544 border=\"0\" ALT=\"Google\"></A>
1545 </td>
1546 <td>
1547 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1548 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1549 <font size=-1>
1550 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
1551 <input type='hidden' name='ie' value='$2'>
1552 <input type='hidden' name='oe' value='$2'>
1553 </font>
1554 </td></tr></TABLE>
1555 </FORM>
1556 <!-- SiteSearch Google -->";
1557 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1558
1559
1560 if( !headers_sent() ) {
1561 header( 'HTTP/1.0 500 Internal Server Error' );
1562 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1563 /* Don't cache error pages! They cause no end of trouble... */
1564 header( 'Cache-control: none' );
1565 header( 'Pragma: nocache' );
1566 }
1567 $msg = wfGetSiteNotice();
1568 if($msg == '') {
1569 $msg = str_replace( '$1', $error, $noconnect );
1570 }
1571 $text = $msg;
1572
1573 if($wgUseFileCache) {
1574 if($wgTitle) {
1575 $t =& $wgTitle;
1576 } else {
1577 if($title) {
1578 $t = Title::newFromURL( $title );
1579 } elseif (@/**/$_REQUEST['search']) {
1580 $search = $_REQUEST['search'];
1581 echo $searchdisabled;
1582 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1583 $wgInputEncoding ), $googlesearch );
1584 wfErrorExit();
1585 } else {
1586 $t = Title::newFromText( $mainpage );
1587 }
1588 }
1589
1590 $cache = new CacheManager( $t );
1591 if( $cache->isFileCached() ) {
1592 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1593 $cachederror . "</b></p>\n";
1594
1595 $tag = '<div id="article">';
1596 $text = str_replace(
1597 $tag,
1598 $tag . $msg,
1599 $cache->fetchPageText() );
1600 }
1601 }
1602
1603 echo $text;
1604 wfErrorExit();
1605 }
1606
1607 ?>